package com.itheima.filter;


import com.itheima.Utils.BaseContext;
import com.itheima.Utils.PathMatcherUtil;
import com.itheima.entity.Employee;
import com.itheima.entity.User;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//自定义过滤器登录
@Slf4j
@WebFilter
public class LoginFilter implements Filter {
    //登录逻辑处理
    @Override
    public void doFilter(ServletRequest httpServletRequest, ServletResponse httpServletResponse, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) httpServletRequest;//请求
        HttpServletResponse response = (HttpServletResponse) httpServletResponse;//响应
        //1、获取本次请求的URI
        log.debug("request.getRequestURL()" + request.getRequestURL());
        log.debug("request.getRequestURI()" + request.getRequestURI());
        String requestURI = request.getRequestURI();
        //2、判断本次请求是否需要处理
        String[] urls = new String[]{
                "/**/api/**", "/**/images/**", "/**/js/**", "/**/plugins/**", "/**/styles/**",
                "/**/favicon.ico", "/**/fonts/**", "/**/login.html", "/employee/login", "/employee/logout",
                "/user/sendMsg", "/user/login"

        };
        boolean isCheck = PathMatcherUtil.check(urls, requestURI);
        log.debug("**登录requestURI{}匹配结果为{}**", requestURI, isCheck);
        //3、如果不需要处理，则直接放行
        if (isCheck) {//true:放行
            chain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //4,不放行，从session中获取employee对象
        Employee employee = (Employee) request.getSession().getAttribute("employee");

        //5、判断登录状态，如果已登录，则直接放行   //5.session中employee对象，放行
        if (employee != null) {
            BaseContext.setCurrentId(employee.getId());
            log.debug("**用户已登录**" + employee.toString());
            chain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //6.不放行，从session中获取user对象
        User user = (User) request.getSession().getAttribute("user");
        //7.session中user对象，放行
        if (user != null) {
            //5.1 用户已经登录，将用户id存入本地线程对象ThreadLocal(可以保证线程安全)
            BaseContext.setCurrentId(user.getId());//设置用户id 以后可以根据你的需求来存数据
            log.debug("**移动端用户已登录**" + user.toString());
            chain.doFilter(httpServletRequest, httpServletResponse);
            return;
        }
        //8.session中不存在employee对象，跳转登录页面
        if (requestURI.contains("backend")){
            response.sendRedirect("/backend/page/login/login.html");
        }else {
            //跳转移动端登录页面
            response.sendRedirect("/front/page/login.html");
        }
        log.debug("**用户未登录跳转首页了**");
    }


}
